﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32.TaskScheduler;

namespace SQLServerOptimizer.PL.WPF
{
    public class SchedulePerfTask
    {
        public void CreateTask(int traceid, DateTime Start, DateTime End)
        {
            try
            {

                using (TaskService ts = new TaskService())
                {

                    TaskDefinition td = ts.NewTask();
                    td.RegistrationInfo.Description = "";
                    TimeTrigger tt = new TimeTrigger();
                    tt.StartBoundary = Start;
                    tt.EndBoundary = End;
                    tt.Repetition.Interval = TimeSpan.FromMinutes(10);

                    td.Triggers.Add(tt);

                    td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(2);

                    td.Actions.Add(new ExecAction(System.Windows.Forms.Application.StartupPath + @"\SQLServerOptimizer.PL.WPF.exe", "PerformanceTrace " + traceid, null));

                    ts.RootFolder.RegisterTaskDefinition(@"SQLServerOptimizerMonitor" + traceid, td);

                }
            }
            catch (Exception ex)
            {

            }
        }

        public void removetask(int traceid)
        {
            using (TaskService ts = new TaskService())
            {
                try
                {
                    ts.RootFolder.DeleteTask(@"SQLServerOptimizerMonitor" + traceid);

                }
                catch
                {


                }
            }
        }
    }
}
